package com.gopay.checkorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.HxbcConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.hxbc.ebank.query.req.BodyB2CReqQuery;
import com.gopay.common.domain.bank.hxbc.ebank.query.req.HXEB2CReqQuery;
import com.gopay.common.domain.bank.hxbc.ebank.query.res.BodyB2CResQuery;
import com.gopay.common.domain.bank.hxbc.ebank.query.res.HXEB2CResQuery;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.BankInteractRemoteService;

public class CheckOrderHxbcB2cImpl implements BankOrderService {
	
	private final static Logger logger = LoggerFactory.getLogger("HXBC");
	
	 @Resource(name = "bankClient")
	 private BankInteractRemoteService bankClient;
	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
		
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
        checkOrderResult.setOrderId(bankOrder.getOrderId());
        try {
        	HXEB2CReqQuery base = new HXEB2CReqQuery();
    		BodyB2CReqQuery bodyQuery = new BodyB2CReqQuery();
			base.setOrderId(bankOrder.getOrderId());
			base.setBankOrderId(bankOrder.getOutOrderId());
			base.setBank(BankConstants.BANK_LOGO_HXBC);
			base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
			base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
			bodyQuery.setOrderNo(bankOrder.getOrderId());
			base.setBody(bodyQuery);
	
	        Result result = new Result();	       
	        result = bankClient.query(base);	        
	
	        if (result == null || !result.isSuccess() || result.getDefaultModel() == null) {
	            logger.error("bankClient fail.");
	            
	            if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
	            	BankCountDownLatch.failIncrease(bankOrder.getBankCode());
	            	checkOrderResult.setCommunicateError(true);
				}
	            checkOrderResult.setSuccess(false);
				checkOrderResult
						.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
	        }
	
	        HXEB2CResQuery res = (HXEB2CResQuery) result.getDefaultModel();
	        if (res == null) {
	        	// 查询订单为空
				logger.error("fail:orderId:" + bankOrder.getOrderId()+ " errcode:" + ProcCodeConstants.PROC_CODE_100E6022+ " err:bis query is null.");
				checkOrderResult.setSuccess(false);
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("银行返回对账结果为空");
				return checkOrderResult;
	        }
	
	        if (res.getHead().getRespCode().equals(HxbcConstants.RESPCODE_OTHER)) {
	            // 查询订单错误
	            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + res.getHead().getRespDescp() + " err:"+ res.getHead().getRespDescp());
	            checkOrderResult.setSuccess(false);
	            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
	            checkOrderResult.setErrMsg(res.getHead().getRespDescp());
	            return checkOrderResult;
	        }
	        if(res.getHead().getRespCode() != null && !res.getHead().getRespCode().equals("")){
	                // 有可能是订单号错或者其他错误，滞后处理
	     			if (res.getHead().getRespCode().equals(HxbcConstants.RESPCODE_NOTFOUND)) {
	     				checkOrderResult.setSuccess(false);
						logger.error("华夏银行B2C订单:" + bankOrder.getOutOrderId()+ ",交易成功返回信息：未成功支付或订单不存在或其他错误,查询返回码："+ res.getHead().getRespCode());
				        checkOrderResult.setErrMsg("未成功支付或订单不存在或其他错误");
	     			}
	     			// 订单处理中
	     			else if (res.getHead().getRespCode().equals(HxbcConstants.RESPCODE_PROSESSING)) {
	     				checkOrderResult.setSuccess(false);
						logger.error("华夏银行B2C订单:" + bankOrder.getOutOrderId()+ ",交易成功返回信息：订单正在处理中,查询返回码："+ ",查询返回码：" + res.getHead().getRespCode());
				         checkOrderResult.setErrMsg("订单正在处理中");
	     			}
	     			// 订单处理完成
	     			else{
	     				BodyB2CResQuery resMsg = res.getBody();
	     				BigDecimal originalAmount = new BigDecimal(resMsg.getOrderAmt());
	    				String resultStr = originalAmount.divide(new BigDecimal(100)).toString();
	    				BigDecimal amount = BigDecimal.valueOf(Double.valueOf(resultStr));
	    				if (StringUtils.isEmpty(resMsg.getStatus())) {
	    					logger.error("华夏B2C订单:" + bankOrder.getOutOrderId()+ ",没有查到相应的 订单状态,错误信息为：" + res.getHead().getRespDescp());
	    			        checkOrderResult.setErrMsg(res.getHead().getRespDescp());
	    			        checkOrderResult.setSuccess(false);
	    				}
	    				
	    				// 订单状态成功(订单已支付)
	    				if (HxbcConstants.TRADE_SUCCESS.equals(resMsg.getStatus())) {
	    					logger.error("华夏B2C订单" + bankOrder.getOutOrderId() + "交易成功("+ resMsg.getStatus() + ")");
	    					checkOrderResult.setSuccess(true);
	    					InAccInfo accInfo = new InAccInfo();
							accInfo.setOrderId(bankOrder.getOrderId());
							accInfo.setAmount(amount);
							accInfo.setRetCode("00");
							accInfo.setCardType(BankCardType.Unknown.toString());
							checkOrderResult.setAccInfo(accInfo);
	    					
	    				} else if (HxbcConstants.TRADE_FAIL.equals(resMsg.getStatus())) {
	    					logger.error("华夏B2C订单" + bankOrder.getOutOrderId() + "交易失败("+ resMsg.getStatus() + ")");
	    			        checkOrderResult.setErrMsg(res.getHead().getRespDescp());
	    			        checkOrderResult.setSuccess(false);
	    			
	    				} else {
	    					logger.error("华夏B2C订单:" + bankOrder.getOutOrderId() + "交易结果未明确("+ resMsg.getStatus() + ")，跳过");
	    			        checkOrderResult.setErrMsg(res.getHead().getRespDescp());
	    			        checkOrderResult.setSuccess(false);
	    				}
	           }
            }else{
	        	   logger.error(" HXBC B2C orderId:" + bankOrder.getOrderId()+ ",returnMsg:  订单未查到");
					checkOrderResult.setSuccess(false);
					checkOrderResult.setErrMsg("银行返回订单未查到");
	          }
	        return checkOrderResult;
        } catch (Exception e) {
            logger.error("bankClient fail.", e);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("系统对账异常");
            return checkOrderResult;
        }
    }
	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}
}
